package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.Announcement;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 公告信息数据访问层接口
 * 继承自MyBatis-Plus的BaseMapper，自动具备基础的CRUD功能
 * 包括但不限于以下方法：
 * - insert(T entity): 插入一条记录
 * - deleteById(ID id): 根据ID删除一条记录
 * - updateById(T entity): 根据ID更新一条记录
 * - selectById(ID id): 根据ID查询一条记录
 * - selectList(Wrapper<T> queryWrapper): 根据条件查询记录列表
 */
@Mapper
@Repository
public interface AnnouncementMapper extends BaseMapper<Announcement> {

    /**
     * 查询所有已发布的公告
     * 只返回is_published为true的公告记录
     * 结果按发布时间（publish_time）降序排序，最新发布的排在前面
     *
     * @return 已发布的公告列表
     */
    @Select("SELECT * FROM announcements WHERE is_published = true ORDER BY publish_time DESC")
    List<Announcement> findAllPublished();
    /**
     * 分页查询已发布的公告
     */
    @Select("SELECT * FROM announcements WHERE is_published = true ORDER BY publish_time DESC LIMIT #{size} OFFSET #{offset}")
    List<Announcement> findPublishedWithPage(@Param("offset") int offset, @Param("size") int size);


    /**
     * 获取已发布公告的总数
     */
    @Select("SELECT COUNT(*) FROM announcements WHERE is_published = true")
    long countPublished();


    /**
     * 查询所有公告记录
     * 返回所有公告（包括已发布和未发布的）
     * 结果按创建时间（create_time）降序排序，最新创建的排在前面
     *
     * @return 所有公告记录列表
     */
    @Select("SELECT * FROM announcements ORDER BY create_time DESC")
    List<Announcement> findAllOrderByCreateTime();
    /**
     * 分页查询公告（支持状态筛选）
     */
    @Select("<script>" +
            "SELECT a.*, u1.username as creator_name, u2.username as modifier_name " +
            "FROM announcements a " +
            "LEFT JOIN users u1 ON a.created_by = u1.id " +
            "LEFT JOIN users u2 ON a.last_modified_by = u2.id " +
            "<where>" +
            "<if test='status != null'>" +
            "   AND a.is_published = #{status}" +
            "</if>" +
            "</where>" +
            "ORDER BY a.create_time DESC " +
            "LIMIT #{size} OFFSET #{offset}" +
            "</script>")
    List<Announcement> findAllWithPage(@Param("offset") int offset,
                                       @Param("size") int size,
                                       @Param("status") Integer status);

    /**
     * 获取公告总数（支持状态筛选）
     */
    @Select("<script>" +
            "SELECT COUNT(*) FROM announcements " +
            "<where>" +
            "<if test='status != null'>" +
            "   AND is_published = #{status}" +
            "</if>" +
            "</where>" +
            "</script>")
    long countAll(@Param("status") Integer status);
}